package tech.mhuang.pacebox.springboot.wechat.wechat.common.service;

import tech.mhuang.pacebox.core.util.StringUtil;
import tech.mhuang.pacebox.springboot.wechat.wechat.common.consts.WechatConsts;

import java.util.Map;

/**
 * 微信核心服务（使用请继承）
 *
 * @author mhuang
 * @since 1.0.0
 */
public abstract class BaseWechatService extends BaseWechatEventService {

    public static final String WECHAT_SUBSCRIBE = "1";
    public static final String WECHAT_UNSUBSCRIBE = "2";

    private static final String VOICE_MSG = "voice";
    private static final String VIDEO_MSG = "video";
    private static final String SHORT_VIDEO_MSG = "shiroVideo";
    private static final String LOCATION_MSG = "location";
    private static final String LINK_MSG = "link";

    /**
     * 微信事件监听统一管理方法
     *
     * @param wechatParamsMap 微信参数Map
     * @return 应答的消息内容
     * @throws Exception 异常
     */
    public String manager(Map<String, String> wechatParamsMap) throws Exception {
        String msgType = wechatParamsMap.get("MsgType");
        //事件推送
        if (msgType.equals("event")) {
            return event(wechatParamsMap);
            //非事件
        }
        return other(wechatParamsMap);
    }

    private String event(Map<String, String> map) {
        String openId = map.get("FromUserName"),
                eventType = map.get("Event"),
                appId = map.get("ToUserName"),
                eventKey = map.get("EventKey");
        switch (eventType) {
            //订阅
            case "subscribe" -> {
                if (StringUtil.isEmpty(eventKey)) {
                    return subscribe(openId, appId);
                } else {
                    return subscribe(openId, appId, eventKey);
                }
            }
            //取消订阅
            case "unsubscribe" -> {
                return unSubscribe(openId, appId);
            }
            //点击菜单拉取消息时的事件推送
            case "CLICK" -> {
                return click(openId, appId, eventKey);
            }
            //用户点击view页面
            case "VIEW" -> {
                return view(openId, appId, eventKey);
            }
            case "SCAN" -> {
                return scan(openId, appId, eventKey);
            }
            default -> {
                return null;
            }
        }
    }

    private String other(Map<String, String> map) {
        String msgType = map.get("MsgType"),
                appId = map.get("ToUserName"),
                openId = map.get("FromUserName");
        return switch (msgType) {
            case WechatConsts.TEXT -> textMsg(openId, appId, map.get("Content"));
            case WechatConsts.IMAGE -> imageMsg(openId, appId);
            case VOICE_MSG, VIDEO_MSG, SHORT_VIDEO_MSG, LOCATION_MSG, LINK_MSG -> null;
            default -> null;
        };
    }
}
